package com.ypf.rpc.nettyHandler;

import com.ypf.rpc.message.HeartMessage;
import com.ypf.rpc.message.Message;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class RegisterHeartBeatClientHandler extends ChannelDuplexHandler {

    /**
     * 写空闲事件
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent){
            IdleState state = ((IdleStateEvent) evt).state();
            if (state==IdleState.WRITER_IDLE){
                // 获取ip
                log.debug("服务器向注册中心发送心跳包 {}", ctx.channel().remoteAddress());
                HeartMessage heartMessage = new HeartMessage();
                heartMessage.setSequenceId(0);
                heartMessage.setMessageType(Message.heartMessage);
                /**
                 * 向所有通信过的注册中心发心跳
                 */
                ctx.writeAndFlush(heartMessage).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
            }
        }else {
            super.userEventTriggered(ctx, evt);
        }

    }


}
